<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { logger } from '../utils/logger'
import { wsManager } from '../../utils/websocket'

// 路由
const router = useRouter()

// 更新时间函数
const updateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

// 按钮状态
const buttonStates = ref({
  home: '正常',
  user: '正常',
  dataImport: '正常',
  dataManage: 'normal',
  dataAnnotation: 'normal'
})

// 获取当前时间
const currentTime = ref('')

// WebSocket连接状态
const wsConnected = ref(false)

// 初始化WebSocket连接
const initWebSocket = async () => {
  try {
    if (!wsManager.ws || wsManager.ws.readyState !== WebSocket.OPEN) {
      await wsManager.connect()
    }
    wsConnected.value = true
  } catch (error) {
    console.error('WebSocket连接失败:', error)
  }
}

onMounted(() => {
  document.addEventListener('click', handleDocumentClick)
  initWebSocket()
  getWeightList() // 添加这行调用获取权重列表
  
  // 添加WebSocket消息监听
//   const messageHandler = (event) => {
//     const response = JSON.parse(event.data)
//     if (response.operation === 'dataheartbeat') {
//       // 转换数据格式
//       datasets.value = response.params.map(item => ({
//         datasetId: item.id,
//         name: item.id,
//         status: item.status,
//         progress: item.progress,
//         lastModified: item.last_modified,
//         size: item.size,
//         attribute: item.attribute
//       }))
      
//       // 检查当前数据集ID是否匹配
//       if (currentDataset.value && filterDialogVisible.value) {
//         const matchedDataset = response.params.find(item => item.id === currentDataset.value.datasetId)
//         if (matchedDataset && matchedDataset.status === 'autofiltering') {
//           autoFilterProgress.value = matchedDataset.progress
//         }
//       }
//     }
//   }
  
//   wsManager.ws.addEventListener('message', messageHandler)
  
//   // 保存handler引用以便卸载时移除
//   window._currentMessageHandler = messageHandler
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick)
//   // 移除WebSocket消息监听
//   if (wsManager.ws && window._currentMessageHandler) {
//     wsManager.ws.removeEventListener('message', window._currentMessageHandler)
//     delete window._currentMessageHandler
//   }
})
onMounted(() => {
  // 更新时间
  updateTime()
  setInterval(updateTime, 1000)
})

// 在setup函数中添加
const handleDocumentClick = (event) => {
  if (contextMenuVisible.value && !event.target.closest('.context-menu')) {
    contextMenuVisible.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleDocumentClick)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick)
})

// 获取状态图标路径
const getStatusIcon = (status) => {
  switch(status) {
    case 'imported':
      return '/pic/dataManagement/未处理.png'
    case 'formated':
      return '/pic/dataManagement/已格式化.png'
    case 'autofiltered':
      return '/pic/dataManagement/已完成筛选.png'
    default:
      return '/pic/dataManagement/未处理.png'
  }
}

// 返回主页
const goToHome = () => {
  router.push('/')
}

const goToDataManagement = () => {
  router.push('/data-management')
} 

const goToDataAnnotation = () => {
  router.push('/data-annotation')
}

// 鼠标事件处理
const handleMouseEnter = (button) => {
  buttonStates.value[button] = '悬浮'
}

const handleMouseLeave = (button) => {
  buttonStates.value[button] = '正常'
}

const handleMouseDown = (button) => {
  buttonStates.value[button] = '点击'
}

const handleMouseUp = (button) => {
  buttonStates.value[button] = '悬浮'
}

// 权重列表
const weightList = ref([])

// 权重创建用户
const weightCreator = ref('')

// 时间排序方式
const timeSort = ref('时间倒序')

// 获取权重列表
const getWeightList = async (algorithmId) => {
  try {
    // 模拟API请求
    // 实际项目中应该使用axios等工具发送请求
    // const response = await axios.post('/api', {
    //   operation: 'get_algo_weightlist',
    //   params: {
    //     algorithmID: algorithmId
    //   }
    // })
    
    // 模拟数据
    weightList.value = [
      { id: 1, name: '权重A', date: '2023/02/06', score: 0.95, creator: '用户X' },
      { id: 2, name: '权重B', date: '2023/02/06', score: 0.92, creator: '用户Y' },
      { id: 3, name: '权重C', date: '2023/02/06', score: 0.88, creator: '用户X' }
    ]
  } catch (error) {
    console.error('获取权重列表失败:', error)
  }
}
const filteredWeightList = computed(() => {
  let filtered = weightList.value
  
  // 根据创建用户筛选
  if (weightCreator.value) {
    filtered = filtered.filter(weight => weight.creator === weightCreator.value)
  }
  
  // 根据时间排序
  if (timeSort.value === '时间倒序') {
    filtered.sort((a, b) => new Date(b.date) - new Date(a.date))
  } else {
    filtered.sort((a, b) => new Date(a.date) - new Date(b.date))
  }
  
  return filtered
})
</script>

<template>
  <div class="data-management">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <div class="logo">
        <img src="/pic/dataManagement/logo-菜单左上方位置.png" alt="Logo">
      </div>
      <div class="nav-buttons">
        <div class="nav-button"
             @mouseenter="handleMouseEnter('dataManage')"
             @mouseleave="handleMouseLeave('dataManage')"
             @mousedown="handleMouseDown('dataManage')"
             @mouseup="handleMouseUp('dataManage'); goToDataManagement()">
          <img :src="`/pic/dataManagement/数据管理-${buttonStates.dataManage === 'normal' ? '正常' : '悬浮'}.png`" alt="数据管理">
        </div>

        <div class="nav-button"
             @mouseenter="handleMouseEnter('dataAnnotation')"
             @mouseleave="handleMouseLeave('dataAnnotation')"
             @mousedown="handleMouseDown('dataAnnotation')"
             @mouseup="handleMouseUp('dataAnnotation'); goToDataAnnotation()">
          <img :src="`/pic/dataManagement/数据标注-${buttonStates.dataAnnotation === 'normal' ? '正常' : '悬浮'}.png`" alt="数据标注">
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 顶部栏 -->
      <div class="top-bar">
        <div class="system-name">XXXXXXXXXX系统</div>
        <div class="home-button"
             @mouseenter="handleMouseEnter('home')"
             @mouseleave="handleMouseLeave('home')"
             @mousedown="handleMouseDown('home')"
             @mouseup="handleMouseUp('home')"
             @click="goToHome">
          <img :src="`/pic/dataManagement/首页-${buttonStates.home}.png`" alt="首页">
        </div>
        <div class="current-time">{{ currentTime }}</div>
        <div class="user-info">
          <div class="user-button"
               @mouseenter="handleMouseEnter('user')"
               @mouseleave="handleMouseLeave('user')"
               @mousedown="handleMouseDown('user')"
               @mouseup="handleMouseUp('user')">
            <img :src="`/pic/dataManagement/用户-${buttonStates.user}.png`" alt="用户">
          </div>
          <span class="username">用户：XXXX</span>
        </div>
      </div>
      <!-- 在此处添加 -->
      <!-- 权重选择 -->
      <div class="weight-selection">
        <!-- 权重筛选区域 -->
        <div class="weight-filter-area">
          <!-- 权重创建用户 -->
          <div class="weight-creator">
            <span>权重创建用户：</span>
            <select v-model="weightCreator">
              <option value="">全部用户</option>
              <option value="用户X">用户X</option>
              <option value="用户Y">用户Y</option>
            </select>
          </div>
          
          <!-- 时间排序 -->
          <div class="time-sort">
            <span>时间排序方式：</span>
            <select v-model="timeSort">
              <option value="时间正序">时间正序</option>
              <option value="时间倒序">时间倒序</option>
            </select>
          </div>
        </div>
        
        <!-- 权重列表 -->
        <div class="weight-list">
          <div class="weight-item" v-for="weight in filteredWeightList" :key="weight.id">
            <div class="weight-header">
              <input type="radio" :id="`weight-${weight.id}`" name="weight" :value="weight.id">
              <label :for="`weight-${weight.id}`">权重{{ weight.name.slice(-1) }}</label>
            </div>
            <div class="weight-info">
              <div>权重创建用户：{{ weight.creator }}</div>
              <div>创建创建日期：{{ weight.date }}</div>
              <div>得分：{{ weight.score }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 开始评估按钮 -->
      <div class="start-evaluate-button"
           @mouseenter="handleMouseEnter('startEvaluate')"
           @mouseleave="handleMouseLeave('startEvaluate')"
           @mousedown="handleMouseDown('startEvaluate')"
           @mouseup="handleMouseUp('startEvaluate')"
           style="position: fixed; right: 20px; bottom: 20px; background-color: #4a6baf; color: white; padding: 10px 20px; border-radius: 4px; cursor: pointer; transition: background-color 0.3s;">
        开始评估
      </div>
    </div>
  </div>
   
    
</template>

<style scoped>
.data-management {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

.sidebar {
  width: 80px;
  background-color: #4a6baf;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}

.logo img {
  width: 60px;
  height: auto;
}

.nav-buttons {
  margin-top: 20px;
}

.nav-button {
  margin-bottom: 10px;
  cursor: pointer;
}

.nav-button img {
  width: 60px;
  height: auto;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.top-bar {
  height: 60px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.system-name {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.home-button {
  margin-left: 20px;
  cursor: pointer;
}

.current-time {
  margin-left: auto;
  color: #666;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.user-button {
  cursor: pointer;
  margin-right: 10px;
}

.username {
  color: #333;
}

.dataset-management {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.data-import-button {
  margin-bottom: 20px;
  cursor: pointer;
}

.status-legend {
  display: flex;
  margin-bottom: 20px;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-item img {
  width: 20px;
  height: 20px;
}

.dataset-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.dataset-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dataset-image {
  position: relative;
  width: 100%;
  padding-top: 100%;
}

.dataset-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.status-icon {
  position: absolute;
  bottom: 10px;
  left: 10px;
  width: 24px !important;
  height: 24px !important;
}

.dataset-info {
  padding: 10px;
}

.dataset-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
}

.progress-bar {
  height: 4px;
  background-color: #e0e0e0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 5px;
}

.progress {
  height: 100%;
  background-color: #4a6baf;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #666;
  text-align: right;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  min-width: 120px;
}

.context-menu-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.context-menu-item:hover {
  background-color: #f0f2f5;
}

.context-menu-item.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.context-menu-item.disabled:hover {
  background-color: transparent;
}

/* 筛选弹窗样式 */
.filter-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  width: 800px;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}

.filter-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #4a6baf;
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.close-button {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
}

.auto-filter-section {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.auto-filter-button {
  background-color: #4a6baf;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.auto-filter-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.progress-bar-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #4a6baf;
  transition: width 0.3s ease;
}

.transfer-container {
  display: flex;
  padding: 0 16px 16px;
  gap: 16px;
  flex: 1;
  min-height: 300px;
  overflow: hidden;
}

.transfer-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.panel-header {
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  font-weight: bold;
}

.file-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
}

.file-item {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.2s;
}

.file-item.selected {
  border-color: #4a6baf;
  background-color: rgba(74, 107, 175, 0.1);
}

.file-item img {
  width: 100%;
  height: 80px;
  object-fit: cover;
}

.file-name {
  padding: 4px;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
}

.transfer-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
}

.transfer-buttons button {
  background-color: #4a6baf;
  color: white;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 4px;
  cursor: pointer;
}

.filter-dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  gap: 12px;
  border-top: 1px solid #e0e0e0;
}

.cancel-button, .confirm-button {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-button {
  background-color: white;
  border: 1px solid #d9d9d9;
  color: #333;
}

.confirm-button {
  background-color: #4a6baf;
  border: none;
  color: white;
}

/* 数据集详情弹窗样式 */
.detail-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  width: 800px;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.detail-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #4a6baf;
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.detail-content {
  padding: 16px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
  max-height: 70vh;
}

.detail-file-item {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.detail-file-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}
.param-scheme-list,
.weight-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.param-scheme-item,
.weight-item {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
}

.param-scheme-header,
.weight-header {
  font-weight: bold;
  margin-bottom: 5px;
}

.param-scheme-desc {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.weight-filter-area {
  display: flex;
  margin-bottom: 15px;
}

.weight-creator,
.time-sort {
  flex: 1;
  margin-right: 20px;
}

.weight-creator select,
.time-sort select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.weight-info {
  font-size: 14px;
  color: #666;
}
</style>